package com.udg.goodmorning.tweet;


import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.widget.RemoteViews;

/**
 * ウィジェットに関する処理を行う。
 * @author Ippei Shimobou
 *
 */
public class WidgetService extends Service {
	private final String BUTTON_CLICK_ACTION = "BUTTON_CLICK_ACTION";
	private final String TAG = "TWakeCall-WidgetService";

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		if (Utility.DEBUG)
			Log.v(TAG, " into WidgetService");

		/* Make a Intent for Button clicking */
		Intent btIntent = new Intent();
		btIntent.setAction(BUTTON_CLICK_ACTION);
		PendingIntent pendingIntent = PendingIntent.getService(this, 0,
				btIntent, 0);
		RemoteViews remoteViews = new RemoteViews(getPackageName(),
				R.layout.widget);
		remoteViews.setOnClickPendingIntent(R.id.imageView1, pendingIntent);

		/* Get the SharedPrefs */
		SharedPreferences sp = getSharedPreferences(getPackageName()
				+ "_preferences", MODE_PRIVATE);
		SharedPreferences.Editor spe = sp.edit();

		Boolean OnOff = sp.getBoolean(Utility.KEY_ONOFF, false);

		/* Set the Image Data */
		if (OnOff) {
			remoteViews.setImageViewResource(R.id.imageView1,
					R.drawable.sample1);
		} else {
			remoteViews.setImageViewResource(R.id.imageView1,
					R.drawable.sample2);
		}

		if (BUTTON_CLICK_ACTION.equals(intent.getAction())) {
			/* When Button clicking, Call this Method */
			if (Utility.DEBUG)
				Log.v(TAG, "Touch Widget");

			/* Check the Account */
			SharedPreferences checkAcc = getSharedPreferences("token",
					MODE_PRIVATE);
			String token = checkAcc.getString("token", "");

			if (token.equals("")) {
				/* Send to MainActivity(preferenceActivity) */
				callMainActivity();
			} else {
				/* Create AlarmManager */
				Intent wakeUpIntent = new Intent(WidgetService.this,
						Receiver.class);
				wakeUpIntent.setAction(Utility.START_SERVICE);
				PendingIntent sender = PendingIntent.getBroadcast(
						WidgetService.this, 0, wakeUpIntent, 0);
				AlarmManager am = (AlarmManager) (WidgetService.this
						.getSystemService(ALARM_SERVICE));

				if (OnOff) {
					if (Utility.DEBUG)
						Log.v(TAG, "Change to OFF State");

					/* Change to OFF State */
					remoteViews.setImageViewResource(R.id.imageView1,
							R.drawable.sample2);

					/* Stop the AlarmManager */
					am.cancel(sender);

				} else {
					if (Utility.DEBUG)
						Log.v(TAG, "Change to ON State");

					/* Change to ON State */
					remoteViews.setImageViewResource(R.id.imageView1,
							R.drawable.sample1);

					/* Setting On-Time */
					SharedPreferences OnOffPref = getSharedPreferences(
							"on_off_time", MODE_PRIVATE);
					SharedPreferences.Editor editor = OnOffPref.edit();
					/* Get time */
					editor.putString("on_time",
							Long.toString(System.currentTimeMillis()));
					editor.commit();

					/* Get interval time */
					String preftime = sp.getString(Utility.KEY_TIME_LIST, "5");

					/* set manager */
					long interval = Long.valueOf(preftime) * 1000 * 60;

					if (Utility.DEBUG)
						interval = 1000 * 60;

					long firstTime = SystemClock.elapsedRealtime();
					am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
							firstTime, interval, sender);
				}
				spe.putBoolean(Utility.KEY_ONOFF, !OnOff);
				spe.commit();
			}
		}

		ComponentName thisWidget = new ComponentName(this, Widget.class);
		AppWidgetManager manager = AppWidgetManager.getInstance(this);
		manager.updateAppWidget(thisWidget, remoteViews);
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	private void callMainActivity(){
		Intent cIntent = new Intent(WidgetService.this,PreferenceMenu.class);
		cIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(cIntent);
	}
}